package main

import (
	"fmt"
	"io"
	"net"
	"sync"
	"time"
)

type Server struct {
	Ip   string
	Port int
	//在线用户列表
	OnlineMap map[string]*User
	mapLock   sync.RWMutex

	//消息广播的channel
	Message chan string
}

//创建一个server的接口
func NewServer(ip string, port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string),
	}
	return server

}

//监听message广播消息channel的goroutine 一旦有消息就发送给全部的在线uers
func (this *Server) ListenMessager() {
	for {
		msg := <-this.Message
		//将msg发送给全部的在线user
		this.mapLock.Lock()

		for _, cli := range this.OnlineMap {
			cli.C <- msg
		}
		this.mapLock.Unlock()
	}
}

//广播消息
func (this *Server) BoradCast(user *User, msg string) {
	sendMsg := "[" + user.Addr + "]" + user.Name + ":" + msg
	this.Message <- sendMsg

}

//处理的业务多该如何处理
func (this *Server) Handler(conn net.Conn) {
	//..当前连接业务
	fmt.Println("连接成功")

	user := NewUser(conn, this)
	/*封装到user Online
	//用户上线，将用户加入到onlineMap种,加锁防止脏数据
	this.mapLock.Lock()
	this.OnlineMap[user.Name] = user
	this.mapLock.Unlock()

	//广播当前用户上线消息
	this.BoradCast(user, "已上线")
	*/
	//用户上线
	user.Online()

	//监听用户是否活跃的channel
	isLive := make(chan bool)

	//接受客户端发送的消息
	go func() {
		buf := make([]byte, 4096)
		for {
			n, err := conn.Read(buf)
			//判断读取的数据为0 表示正常下线
			if n == 0 {
				//this.BoradCast(user, "下线")
				user.Offline()
				return
			}
			if err != nil && err != io.EOF {
				fmt.Println("conn.Read err:", err)
				return
			}

			//提取用户的消息,进行广播（减一是去除‘\n’）
			msg := string(buf[:n-1])
			//this.BoradCast(user, msg)
			user.DoMessage(msg)
			isLive <- true

		}
	}()

	//当前handler阻塞
	for {
		select {
		case <-isLive:
		//是什么都不做，为了激活select 更新下面的定时器
		case <-time.After(time.Second * 300):
			//已经超时

			//将当前user强制的关闭
			user.SendMsg("你被踢了\n")

			close(user.C)
			//关闭连接为什么 map里面用户也没有了
			conn.Close()

			return

		}
	}

}

func (this *Server) Start() {
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", this.Ip, this.Port))
	if err != nil {
		fmt.Println("net.listen err:", err)
		return
	}

	defer listener.Close()

	//启动监听 Mesaage的goroutine
	go this.ListenMessager()

	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("listern Accept err:", err)
			continue
		}
		// do  handler
		go this.Handler(conn)

	}

}
